import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:ecy_app_flutter/routes/consignment/model/ConsignOrder.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../../../EcyRouter.dart';
import '../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../model/EcyApiCommonPage.dart';
import '../../../model/EcyApiCommonResponse.dart';

class EcyMyBuyListPage extends StatefulWidget {
  const EcyMyBuyListPage({required super.key});

  @override
  State<EcyMyBuyListPage> createState() => _EcyMyBuyListPageState();
}

class _EcyMyBuyListPageState extends State<EcyMyBuyListPage>
    with SingleTickerProviderStateMixin {
  _EcyMyBuyListPageState();

  /// 商品状态：-1:锁定（下单=>再卖）0:草稿、1:上架、2:已售出、3:已下架，默认为草稿
  final List<String> tabs = ['全部', '待寄存', '待取货', '已完成'];
  late TabController _tabController;
  final List<ScrollController> _tabScrollControllers = [];
  int _currentPage = 1;
  bool _hasMore = false;
  bool showToTopBtn = false;
  bool isLoading = false;

  String _status = "";

  final List<ConsignOrder> _consignOrderList = [];

  // 添加刷新控制器
  late List<RefreshController> _refreshControllers;

  @override
  void initState() {
    super.initState();

    // 初始化刷新控制器
    _refreshControllers = List.generate(
      tabs.length,
          (index) => RefreshController(initialRefresh: false),
    );

    _tabController = TabController(length: tabs.length, vsync: this);
    _tabController.addListener(() {
      if (_tabController.animation!.value == _tabController.index) {
        _handleTabSelection(_tabController.index); //获取点击或滑动页面的索引值
      }
    });

    // 初始化每个 Tab 页的控制器
    for (int i = 0; i < tabs.length; i++) {
      ScrollController scrollController = ScrollController();
      _tabScrollControllers.add(scrollController);
      scrollController.addListener(() {
        if (scrollController.position.pixels >=
            scrollController.position.maxScrollExtent) {
          if (!isLoading) {
            _onLoadMore(i);
          }
        }

        if (scrollController.offset < 300 && showToTopBtn) {
          setState(() {
            showToTopBtn = false;
          });
        } else if (scrollController.offset >= 300 && showToTopBtn == false) {
          setState(() {
            showToTopBtn = true;
          });
        }
      });
    }

    requestData(1);
  }

  @override
  void dispose() {
    // 清理控制器，避免内存泄漏
    _tabController.dispose();
    // 释放所有控制器
    for (var controller in _tabScrollControllers) {
      controller.dispose();
    }
    super.dispose();
  }

  _handleTabSelection(index) {
    setState(() {
      _status = index == 0
          ? ''
          : index == 1
              ? "0"
              : index == 2
                  ? "1"
                  : index == 3
                      ? "2"
                      : "3";
    });
    requestData(1);
  }

  // 修改刷新方法
  Future<void> _onRefresh(int tabIndex) async {
    _currentPage = 1;
    await requestData(_currentPage);
    // 重置上拉加载状态
    _refreshControllers[tabIndex].refreshCompleted();
    if (_hasMore) {
      _refreshControllers[tabIndex].loadComplete();
    } else {
      _refreshControllers[tabIndex].loadNoData();
    }
  }

  // 修改加载更多方法
  Future<void> _onLoadMore(int tabIndex) async {
    if (_hasMore) {
      _currentPage++;
      await requestData(_currentPage);
      _refreshControllers[tabIndex].loadComplete();
    } else {
      _refreshControllers[tabIndex].loadNoData();
    }
  }


  //查询我的寄售 商品状态：-1:锁定（下单=>再卖）0:草稿、1:上架、2:已售出、3:已下架，默认为草稿
  Future<void> requestData(page) async {
    Map<String, dynamic> body = {
      "size": 10,
      "current": page,
      "status": _status,
      "type": "1"
    };
    var response = await EcyRequestbasemanager()
        .post("/app/api/app/consign/order/page", body);

    if (response != null) {
      var commonResponse =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (commonResponse.code == 0 || commonResponse.code == 200) {
        EcyApiCommonPage<ConsignOrder> commonPage = EcyApiCommonPage.fromJson(
            response["data"], (json) => ConsignOrder.fromJson(json));
        _hasMore = (commonPage.pages ?? 0) > _currentPage;
        _currentPage = commonPage.current ?? 0;
        var consignOrderList = commonPage.records ?? [];
        if (page == 1) {
          _consignOrderList.clear();
        }
        setState(() {
          _consignOrderList.addAll(consignOrderList);
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    Widget avatar = Image.asset('assets/images/ic_head.jpg', width: 24);
    Widget image = Image.asset('assets/images/ic_head.jpg', width: 80);

    return DefaultTabController(
        length: tabs.length,
        child: Scaffold(
          backgroundColor: const Color(0xFFF5F5F5),
          appBar: AppBar(
              leadingWidth: 50.w,
              leading: GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () {
                  EcyRouter.pop(context, "");
                },
                child: Align(
                  alignment: Alignment.centerRight,
                  child: Image.asset(
                    "assets/images/ic_back.png",
                    width: 30.w,
                  ),
                ),
              ),
              titleSpacing: 0,
              title: Text('我买到的',
                  style: TextStyle(
                      fontFamily: "PingFang SC",
                      fontWeight: FontWeight.w700,
                      fontSize: 16.sp,
                      color: const Color(0xFF262626))),
              centerTitle: true,
              backgroundColor: Colors.white,
              bottom: PreferredSize(
                preferredSize: const Size.fromHeight(40),
                child: Material(
                  color: const Color(0xFFF5F5F5),
                  child: TabBar(
                    controller: _tabController,
                    labelStyle: TextStyle(
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w700,
                        fontSize: 18.sp,
                        color: const Color(0xFF262626)),
                    unselectedLabelStyle: TextStyle(
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w700,
                        fontSize: 14.sp,
                        color: const Color(0xFF8C8C8C)),
                    tabs: tabs
                        .map((e) => Tab(
                              text: e,
                            ))
                        .toList(),
                    indicatorColor: Colors.transparent,
                    overlayColor:
                        const WidgetStatePropertyAll(Colors.transparent),
                    dividerHeight: 0,
                  ),
                ),
              )),
          body: TabBarView(
              controller: _tabController,
              children: _getPagesWidget(tabs, avatar, image)),
          floatingActionButton: !showToTopBtn
              ? null
              : FloatingActionButton(
                  mini: true,
                  backgroundColor: Colors.white,
                  onPressed: () {
                    //返回到顶部时执行动画
                    _tabScrollControllers[_tabController.index].animateTo(
                      0.0,
                      duration: const Duration(milliseconds: 200),
                      curve: Curves.ease,
                    );
                  },
                  child: const Icon(Icons.arrow_upward)),
        ));
  }

  List<Widget> _getPagesWidget(List<String> tabs, Widget avatar, Widget image) {
    return tabs.map((e) {
      final tabIndex = tabs.indexOf(e);
      if (_tabController.index != tabIndex || _consignOrderList.isEmpty) {
        return SmartRefresher(
          enablePullDown: true,
          enablePullUp: false,

          header: const ClassicHeader(
            refreshStyle: RefreshStyle.Follow,
            idleText: '下拉刷新',
            refreshingText: '加载中...',
            completeText: '刷新完成',
            failedText: '刷新失败',
            textStyle: TextStyle(color: Color(0xFF8C8C8C), fontSize: 14),
            releaseText: '松开刷新',
            iconPos: IconPosition.top,
            spacing: 8,
          ),
          controller: _refreshControllers[tabIndex],
          onRefresh:() => _onRefresh(tabIndex),
          child: ListView.builder(
            shrinkWrap: true,
            physics: const AlwaysScrollableScrollPhysics(),
            padding: const EdgeInsets.fromLTRB(10, 0, 10, 10),
            itemCount: 1,
            itemBuilder: (context, index) {
              return Column(children: [
                Image.asset('assets/images/empty/ic_empty_orders.png',
                    width: 150, height: 150),
                const Text('暂无寄售',
                    style: TextStyle(fontSize: 18, color: Colors.grey)),
              ]);
            },
          ),
        );
      }
      return SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        header: const ClassicHeader(
          refreshStyle: RefreshStyle.Follow,
          idleText: '下拉刷新',
          refreshingText: '加载中...',
          completeText: '刷新完成',
          failedText: '刷新失败',
          textStyle: TextStyle(color: Color(0xFF8C8C8C), fontSize: 14),
          releaseText: '松开刷新',
          iconPos: IconPosition.top,
          spacing: 8,
        ),
        footer: CustomFooter(
          builder: (BuildContext context, LoadStatus? mode) {
            Widget body;
            if (mode == LoadStatus.idle) {
              body = const Text("上拉加载更多",
                  style: TextStyle(color: Color(0xFF8C8C8C)));
            } else if (mode == LoadStatus.loading) {
              body = const CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFEA4B9B)),
              );
            } else if (mode == LoadStatus.failed) {
              body = const Text("加载失败，点击重试",
                  style: TextStyle(color: Color(0xFF8C8C8C)));
            } else if (mode == LoadStatus.canLoading) {
              body = const Text("松手加载更多",
                  style: TextStyle(color: Color(0xFF8C8C8C)));
            } else {
              body = const Text("没有更多订单了",
                  style: TextStyle(color: Color(0xFF8C8C8C)));
            }
            return SizedBox(
              height: 35.w,
              child: Center(child: body),
            );
          },
        ),
        controller: _refreshControllers[tabIndex],
        onRefresh: () => _onRefresh(tabIndex),
        onLoading: () => _onLoadMore(tabIndex),
        child: ListView.builder(
          controller: _tabScrollControllers[tabIndex],
          physics: const AlwaysScrollableScrollPhysics(),
          padding: const EdgeInsets.fromLTRB(10, 0, 10, 10),
          itemCount: _consignOrderList.length,
          itemBuilder: (context, index) {
            return _buildCard(_consignOrderList[index], avatar, image);
          },
        ),
      );
    }).toList();
  }

  /// 已取货
  void _orderTake(String orderCode) async {
    try {
      var response = await EcyRequestbasemanager()
          .post("/app/api/app/consign/order/take", {"orderCode": orderCode});
      var commonResponse =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (commonResponse.code == 0 || commonResponse.code == 200) {
        setState(() {
          _consignOrderList.removeWhere((n) => n.orderCode == orderCode);
        });
        EasyLoading.showToast("取货成功", duration: const Duration(seconds: 1));
      }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    }
  }

  Widget _buildCard(ConsignOrder consignOrder, Widget avatar, Widget image) {
    return GestureDetector(
        onTap: () {
          // 进入订单详情
          EcyRouter.push(context, EcyRouter.myConsignmentOrderDetailPage,
              {"orderCode": consignOrder.orderCode, "type": "1"});
        },
        child: Card(
          color: Colors.white,
          margin: const EdgeInsets.only(bottom: 10),
          child: Padding(
            padding: const EdgeInsets.all(10),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          SizedBox(
                            height: 24.w,
                            width: 24.w,
                            child: ClipRRect(
                                borderRadius: BorderRadius.circular(50.0),
                                child: CachedNetworkImage(
                                  width: 24.w,
                                  height: 24.w,
                                  imageUrl: consignOrder.sellerAvatar ?? "",
                                  imageBuilder: (context, imageProvider) => Container(
                                    decoration: BoxDecoration(
                                        borderRadius:
                                        BorderRadius.all(Radius.circular(50.r)),
                                        image: DecorationImage(
                                            image: imageProvider, fit: BoxFit.cover)),
                                  ),
                                  errorWidget: (context, url, error) => avatar,
                                )),
                          ),
                          const Padding(padding: EdgeInsets.only(left: 8)),
                          Text(consignOrder.sellerName ?? '商家名称',
                              style: TextStyle(
                                  fontFamily: "PingFang SC",
                                  fontWeight: FontWeight.w700,
                                  fontSize: 14.sp,
                                  color: const Color(0xFF262626))),
                        ]),
                    Text(
                        consignOrder.status == "0"
                            ? "待寄存"
                            : consignOrder.status == "1"
                                ? "待取货"
                                : consignOrder.status == "2"
                                    ? "已取货"
                                    : "已取消",
                        style: TextStyle(
                            fontFamily: "PingFang SC",
                            fontWeight: FontWeight.w700,
                            fontSize: 16.sp,
                            color: const Color(0xFFF55F4E))),
                  ],
                ),
                const Padding(padding: EdgeInsets.only(top: 12)),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    SizedBox(
                      height: 80.w,
                      width: 80.w,
                      child: ClipRRect(
                          borderRadius: BorderRadius.circular(8.0),
                          child: CachedNetworkImage(
                            width: 80.w,
                            height: 80.w,
                            imageUrl: consignOrder.productMainImageUrl ?? "",
                            imageBuilder: (context, imageProvider) => Container(
                              decoration: BoxDecoration(
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(8.r)),
                                  image: DecorationImage(
                                      image: imageProvider, fit: BoxFit.cover)),
                            ),
                            errorWidget: (context, url, error) => avatar,
                          )),
                    ),
                    SizedBox(
                      height: 70.w,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: const EdgeInsets.only(left: 4),
                            child: Text(consignOrder.productTitle ?? '***',
                                style: TextStyle(
                                    fontFamily: "PingFang SC",
                                    fontWeight: FontWeight.w500,
                                    fontSize: 14.sp,
                                    color: const Color(0xFF262626)),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis),
                          ),
                        ],
                      ),
                    ),
                    Expanded(
                      flex: 1,
                      child: SizedBox(
                        height: 70.w,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            const Padding(padding: EdgeInsets.only(bottom: 2)),
                            Text('￥${consignOrder.productPrice ?? 0.00}',
                                style: TextStyle(
                                    fontFamily: "PingFang SC",
                                    fontWeight: FontWeight.w700,
                                    fontSize: 14.sp,
                                    color: const Color(0xFF262626)),
                                textAlign: TextAlign.right),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
                Row(mainAxisAlignment: MainAxisAlignment.end, children: [
                  consignOrder.status == "1"
                      ? SizedBox(
                          height: 32.w,
                          child: TextButton(
                              onPressed: () {
                                _orderTake(consignOrder.orderCode!);
                              },
                              style: const ButtonStyle(
                                alignment: Alignment.center,
                                foregroundColor:
                                    WidgetStatePropertyAll(Color(0xFFEA4B9B)),
                                side: WidgetStatePropertyAll(BorderSide(
                                    color: Color(0xFFEA4B9B), width: 1)),
                              ),
                              child: const Text(
                                '  已取货  ',
                                style: TextStyle(
                                  height: 1,
                                  leadingDistribution: TextLeadingDistribution
                                      .even, // 设置leading策略
                                ),
                              )),
                        )
                      : Container(),
                  const Padding(padding: EdgeInsets.only(right: 8)),
                  // SizedBox(
                  //   height: 32.w,
                  //   child: TextButton(
                  //       onPressed: () {},
                  //       style: const ButtonStyle(
                  //         alignment: Alignment.center,
                  //         foregroundColor:
                  //             WidgetStatePropertyAll(Color(0xFFEA4B9B)),
                  //         side: WidgetStatePropertyAll(
                  //             BorderSide(color: Color(0xFFEA4B9B), width: 1)),
                  //       ),
                  //       child: const Text(
                  //         '联系老师',
                  //         style: TextStyle(
                  //           height: 1,
                  //           leadingDistribution:
                  //               TextLeadingDistribution.even, // 设置leading策略
                  //         ),
                  //       )),
                  // ),
                ]),
              ],
            ),
          ),
        ));
  }

  // 弹出对话框
  Future<bool?> _showDeleteConfirmDialog(String content) {
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          // title: const Text(''),
          contentPadding: const EdgeInsets.all(0),
          backgroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8.0),
          ),
          content: SizedBox(
            height: 130,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Padding(
                  padding: const EdgeInsets.only(top: 20, bottom: 30),
                  child: Text(
                    content,
                    style: const TextStyle(fontSize: 18),
                  ),
                ),
                const Divider(height: 0, color: Color(0XFFdcdcdc)),
                SizedBox(
                  height: 50,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: DecoratedBox(
                          decoration: const BoxDecoration(
                              border: Border(
                            right: BorderSide(
                              width: 1.0,
                              color: Color(0XFFdcdcdc),
                            ),
                          )),
                          child: TextButton(
                            style: const ButtonStyle(
                              alignment: Alignment.center,
                            ),
                            child: const Text(
                              '我再想想',
                              style:
                                  TextStyle(fontSize: 18, color: Colors.black),
                            ),
                            onPressed: () =>
                                Navigator.of(context).pop(), // 关闭对话框
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: TextButton(
                          child: const Text(
                            '确定',
                            style: TextStyle(
                                fontSize: 18, color: Color(0xFFEA4B9B)),
                          ),
                          onPressed: () {
                            //关闭对话框并返回true
                            Navigator.of(context).pop(true);
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          actionsAlignment: MainAxisAlignment.spaceAround,
          actionsPadding: const EdgeInsets.all(0),
        );
      },
    );
  }
}
